#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022-09-07 14:56
# @Site    :
# @File    : zhangji.py
# @Software: PyCharm
import hashlib,sys
import json
import time
import math
import requests
import datetime
from docxtpl import DocxTemplate
import pandas as pd
import warnings

# 创建获取token函数，token函数是加密后的数据
def md5(data,Authorization):
    data = '{}?61b44513-3d63-47a7-a54f-b8d9f0da4165_Wake_Token_{}'.format(data,Authorization)
    # print(data)
    pa = hashlib.md5(data.encode()).hexdigest()
    return pa
# 通过模拟登录获取指定数据
def json_value(page,allSearch,Authorization):
    # payload = "{\"pageNum\":" + f"{page}" + ",\"pageSize\":200,\"orderKey\":\"created_at\",\"orderType\":\"desc\",\"allSearch\":\"张佶\",\"categoryId\":0,\"ids\":\"\",\"groupId\":0,\"placeId\":0,\"scrapAsset\":0,\"isSelf\":0,\"realCategory\":0}"
    payload = "{\"pageNum\":" + f"{page}" + ",\"pageSize\":200,\"orderKey\":\"created_at\",\"orderType\":\"desc\",\"allSearch\":" + f"\"{allSearch}\"" + ",\"categoryId\":0,\"ids\":\"\",\"groupId\":0,\"placeId\":0,\"scrapAsset\":0,\"isSelf\":0,\"realCategory\":0}"
    # print(payload)
    # print(payload)
    data = json.dumps(json.loads(payload), ensure_ascii=False).replace(' ', '')
    token = md5(data,Authorization)
    url = "https://center.wakethings.com/api/asset/asset/assetList"
    headers = {
        'Host': 'center.wakethings.com',
        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
        'sec-ch-ua-mobile': '?0',
        'Authorization': 'bearer {}'.format(Authorization),
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept': 'application/json, text/plain, */*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        'Wkt-Token': token,
        'sec-ch-ua-platform': '"Windows"',
        'Origin': 'https://center.wakethings.com',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://center.wakethings.com/',
        'Accept-Language': 'zh-CN,zh;q=0.9'
    }
    response = requests.request("POST", url, headers=headers, data=payload.encode('utf-8'))
    # print(page, response.json())
    return response.json()
# 将获取的数据做处理，处理过滤剩下自己需要的数据结构
def cycle(page,allSearch,Authorization):
    response = json_value(page,allSearch,Authorization)
    # print(response)
    total = math.ceil(response.get('data').get('total') / 200)
    # print(total)
    for page in range(2, total+1):
        response = req(page)
    a = response["data"]["rows"]
    list1 = []
    for data in a:
        statusName = data["statusName"]
        usepeoper = data["usepeoper"]
        if statusName == '使用中' and usepeoper == allSearch:
            # a = str("使用状态：") + (data["statusName"])
            # b = str("使用人：") + (data["usepeoper"])
            # c = str("资产GZ编码") + (data["assetId"])
            # d = str("资产S/N号") + (data["S/N"])
            a = data["statusName"]
            b = data["usepeoper"]
            c = data["assetId"]
            d = data["S/N"]
            e = {"使用状态":a,"使用人":b,"资产GZ编码":c,"资产S/N号":d}
            # print(e)
            list1.append(e)
            # print(list1)
    return list1
# 将处理后的数据再次处理，并将指定值传入到word模板中
def excel_w(page,allSearch):
    doc = DocxTemplate("/Users/weidian/Desktop/assets.docx")  # 选定模板
    data = cycle(page,allSearch,Authorization)
    # print(data)
    for value in data:
        # print(value)
        name = value["使用人"]
        GZ = value["资产GZ编码"]
        SN = value["资产S/N号"]
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        context = {'name': name,
                    'gz': GZ,
                    'sn': SN,
                    'date': date
                    }  # 需要替换的内容
        # print(context)
        doc.render(context)  # 渲染替换
        doc.save(name + GZ + "资产转移表.docx")  # 保存
# 获取需要查询的名单
def get_name(path):
    # a = sys.argv[1]
    namelist = []
    df = pd.read_excel(path,header=1)  # 这个会直接默认读取到这个Excel的第一个表单
    # print(df)
    for i in (df["姓名"].values):
        namelist.append(i)
    return namelist
# 通过上方查询到的名单循环调用上方写的函数
def start_action(allSearchlist):
    try:
        for start in allSearchlist:
            # print(start)
            excel_w(1,start)
    except:
        print("程序异常，请确认代码路径、token是否正常，一般Authorization有效期只有一天。")
if __name__ == '__main__':
    #忽略告警
    warnings.filterwarnings('ignore')
    #这是认证钥匙，token基于此字段值做加密的，如果无法模拟登录了那么则需要重新获取替换一下这个值
    Authorization='2b570b69-b3af-4917-9556-5b923091a589'
    #名单路径
    path_init = "/Users/weidian/Downloads/微店/新人入职相关文件/新人入职名单/"
    #通过拼接获取入职名单完整表格
    path = path_init + sys.argv[1] + str(".xlsx")
    allSearchlist= get_name(path)
    start_action(allSearchlist)